package com.lz.yz.outing.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.lz.yz.outing.config.OSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.HashMap;
import java.util.UUID;

@Service
public class UploadOSSFile {

    private static HashMap<String, String> imgTypes = new HashMap<>();

    static {
        imgTypes.put("bmp", "image/bmp");
        imgTypes.put("gif", "image/gif");
        imgTypes.put("png", "image/png");
        imgTypes.put("jpe", "image/jpeg");
        imgTypes.put("jpeg", "image/jpeg");
        imgTypes.put("jpg", "image/jpeg");
        imgTypes.put("pct", "image/pict");
        imgTypes.put("pic", "image/pict");
        imgTypes.put("pict", "image/pict");
    }

    @Autowired
    OSSConfig ossConfig;

    public String uploadFile(InputStream inputStream, String fileName) throws IOException {
        ObjectMetadata meta = new ObjectMetadata();
        String ffHouZhui = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        String name = UUID.randomUUID().toString();
        meta.setContentType(imgTypes.get(ffHouZhui));
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(ossConfig.getEndPoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        ossClient.putObject(ossConfig.getBucketName(), name + "." + ffHouZhui, inputStream, meta);
        // 关闭client
        ossClient.shutdown();
        return ossConfig.getFileUrl() + name + "." + ffHouZhui;
    }
}
